import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, message, Tabs } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import styles from './index.less';
import { login } from '@/services/UserService';
import { sendVerificationCode } from '@/services/AuthService';

interface LoginModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  onRegister: () => void;
}

const LoginModal: React.FC<LoginModalProps> = ({ visible, onCancel, onSuccess, onRegister }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('password');
  const [countdown, setCountdown] = useState(0);

  // 监听 visible 变化，当模态框显示时重置表单
  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [visible, form]);

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleRegister = () => {
    form.resetFields();
    onRegister();
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      const loginData = {
        ...values,
        loginType: activeTab.toUpperCase()
      };
      const loginDataVO = await login(loginData);
      if (loginDataVO) {
        console.log(loginDataVO);
        // 登录成功，保存token
        localStorage.setItem('token', loginDataVO.token);
        // message.success('登录成功');
        form.resetFields();
        localStorage.setItem('user', JSON.stringify(loginDataVO.userInfo));
        onSuccess();
        // 页面刷新
        window.location.reload();
      }
    } catch (error: any) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    try {
      const email = form.getFieldValue('email');
      if (!email) {
        message.error('请输入邮箱');
        return;
      }
      
      await sendVerificationCode(email, 'LOGIN');
      message.success('验证码已发送');
      
      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error: any) {
      message.error(error.message || '发送验证码失败');
    }
  };

  const items = [
    {
      key: 'password',
      label: '密码登录',
      children: (
        <Form
          form={form}
          onFinish={handleSubmit}
          className={styles.loginForm}
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="邮箱"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      )
    },
    {
      key: 'code',
      label: '验证码登录',
      children: (
        <Form
          form={form}
          onFinish={handleSubmit}
          className={styles.loginForm}
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="邮箱"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Input
              placeholder="请输入验证码"
              size="large"
              suffix={
                <Button
                  type="link"
                  disabled={countdown > 0}
                  onClick={handleSendCode}
                >
                  {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                </Button>
              }
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      )
    }
  ];

  return (
    <Modal
      title="登录"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      maskClosable={true}
      destroyOnClose
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={items}
        centered
      />
      <div className={styles.footer}>
        <Button type="link" onClick={handleRegister}>
          还没有账号？立即注册
        </Button>
      </div>
    </Modal>
  );
};

export default LoginModal; 